package faw.car.ccenter.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.UserHandle;
import android.text.TextUtils;

import com.faw.adapterproxy.utils.FLog;

import ltd.qisi.corelib.utils.ReflectUtil;

public class StartServiceUtil {
    private final static String TAG = "StartServiceUtil";

    /**
     * start  service as userId
     *
     * @param context
     * @param pkg
     * @param cls
     * @param userId
     */
    public static void startService(Context context, String pkg, String cls, int userId) {
        FLog.i(TAG, "starService pkg: " + pkg + ", cls: " + cls + ", userId: " + userId + ", start");
        try {
            UserHandle userHandle = (UserHandle) ReflectUtil.invoke(UserHandle.class, null, "of", new Class[]{int.class}, userId);
            if (context != null && !TextUtils.isEmpty(pkg) && !TextUtils.isEmpty(cls)) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ComponentName cn = new ComponentName(pkg, cls);
                intent.setComponent(cn);
                if (cls.toLowerCase().contains("service")) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        ReflectUtil.invoke(Context.class, context, "startForegroundServiceAsUser", intent, userHandle);
                    } else {
                        ReflectUtil.invoke(Context.class, context, "startServiceAsUser", intent, userHandle);
                    }
                } else if (cls.toLowerCase().contains("activity")) {
                    ReflectUtil.invoke(Context.class, context, "startActivityAsUser", intent, userHandle);
                }
                FLog.i(TAG, "starService pkg: " + pkg + ", cls: " + cls + ", userId: " + userId + ", normal end");
            }
        } catch (Exception e) {
            FLog.e(TAG, "starService pkg: " + pkg + ", cls: " + cls + ", userId: " + userId + ", error:" + e);
        }
    }

}
